use std::sync::mpsc;
use std::thread::JoinHandle;

use eframe::egui;

use crate::app_global::load_global_font;

pub fn hello() -> Result<(), eframe::Error> {
    let options = eframe::NativeOptions {
        //窗体大小
        initial_window_size: Some(egui::vec2(1024.0, 768.0)),
        ..Default::default()
    };
    eframe::run_native(
        "My parallel egui App",
        options,
        Box::new(|cc| {
            //加载全局字体
            load_global_font(&cc.egui_ctx);
            Box::new(MyApp::new())
        }),
    )
}

/// State per thread.
/// 线程状态（就是一个子窗体）
struct ThreadState {
    thread_nr: usize,
    title: String,
    name: String,
    age: u32,
}

impl ThreadState {
    fn new(thread_nr: usize) -> Self {
        let title = format!("Background thread {thread_nr}");
        Self {
            thread_nr,
            title,
            name: "Arthur".into(),
            age: 12 + thread_nr as u32 * 10,
        }
    }

    //创建一个新的窗体
    fn show(&mut self, ctx: &egui::Context) {
        let pos = egui::pos2(16.0, 128.0 * (self.thread_nr as f32 + 1.0));
        egui::Window::new(&self.title)
            .default_pos(pos)
            .show(ctx, |ui| {
                ui.horizontal(|ui| {
                    ui.label("Your name: ");
                    ui.text_edit_singleline(&mut self.name);
                });
                ui.add(egui::Slider::new(&mut self.age, 0..=120).text("age"));
                if ui.button("Click each year").clicked() {
                    self.age += 1;
                }
                ui.label(format!("Hello '{}', age {}", self.name, self.age));
            });
    }
}

//新建一个子线程
fn new_worker(
    thread_nr: usize,                 //集合大小（第几个线程）
    on_done_tx: mpsc::SyncSender<()>, //通道发送者
) -> (JoinHandle<()>, mpsc::SyncSender<egui::Context>) {
    //创建同步通道
    let (show_tx, show_rc) = mpsc::sync_channel(0);

    //创建线程
    let handle = std::thread::Builder::new()
        .name(format!("EguiPanelWorker {thread_nr}"))
        //线程执行的任务（接收消息）
        .spawn(move || {
            //创建线程状态
            let mut state = ThreadState::new(thread_nr);
            //接收消息
            while let Ok(ctx) = show_rc.recv() {
                //展示一个新的窗体
                state.show(&ctx);
                //发消息回去
                let _ = on_done_tx.send(());
            }
        })
        .expect("failed to spawn thread");
    //返回线程和该线程对应的消息发送者
    (handle, show_tx)
}

struct MyApp {
    threads: Vec<(JoinHandle<()>, mpsc::SyncSender<egui::Context>)>,
    on_done_tx: mpsc::SyncSender<()>,
    on_done_rc: mpsc::Receiver<()>,
}

impl MyApp {
    fn new() -> Self {
        //创建集合
        let threads = Vec::with_capacity(3);
        //创建同步通道，不缓存消息，接收者接收消息前，发送者会阻塞
        let (on_done_tx, on_done_rc) = mpsc::sync_channel(0);

        let mut slf = Self {
            threads,
            on_done_tx, //消息发送者
            on_done_rc, //消息接收者
        };

        //创建两个子线程
        slf.spawn_thread();
        slf.spawn_thread();

        slf
    }

    fn spawn_thread(&mut self) {
        let thread_nr = self.threads.len();
        //创建子线程放到集合中
        self.threads
            //Sender是可以clone的，这样就可以支持多个发送者 可以有多个发送者
            .push(new_worker(thread_nr, self.on_done_tx.clone()));
    }
}

impl std::ops::Drop for MyApp {
    fn drop(&mut self) {
        for (handle, show_tx) in self.threads.drain(..) {
            std::mem::drop(show_tx);
            handle.join().unwrap();
        }
    }
}

impl eframe::App for MyApp {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        egui::Window::new("Main thread").show(ctx, |ui| {
            if ui.button("Spawn another thread").clicked() {
                //创建一个子线程
                self.spawn_thread();
            }
        });

        //给集合中的所有子线程发消息
        for (_handle, show_tx) in &self.threads {
            let _ = show_tx.send(ctx.clone());
        }

        //接收子线程返回的消息
        for _ in 0..self.threads.len() {
            let _ = self.on_done_rc.recv();
        }
    }
}
